package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

@RestController
@RequestMapping("validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 发送验证码到手机
     *
     * @param telephone
     * @return
     */
    @RequestMapping("send2telephone")
    public Result send2Telephone(@RequestParam("telephone") String telephone) {

        try {
            //通过工具类随机获取一个验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            //调用工具类，发送验证码到手机
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());
            //设置一个key，用来保存验证码
            String key = telephone + RedisMessageConstant.SENDTYPE_ORDER;
            //将验证码保存到redis中保存10分钟
            jedisPool.getResource().setex(key, 60 * 10, code.toString());

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }

    /**
     * 快速登录发送验证码
     */
    @RequestMapping("send2login")
    public Result send2login(@RequestParam("telephone") String telephone) {

        try {
            //生成一个随机的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            //将验证码发送到指定的手机
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code);

            //设置保存验证码的redis的key
            String key = telephone + RedisMessageConstant.SENDTYPE_LOGIN;

            //将验证码保存到redis中
            jedisPool.getResource().setex(key, 60 * 10, code);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @RequestMapping("code/{deviceId}")
    public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = defaultKaptcha.createText();
        //生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        //生成的验证码写入redis
        jedisPool.getResource().setex(deviceId, 60 * 5, text);
        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        //将图片写回浏览器
        ImageIO.write(image, "JPEG", out);
    }

    @RequestMapping("judgeCode")
    public Result judgeCode(@RequestParam("imgCode") String imgCode, @RequestParam("deviceId") String deviceId) {
        try {
            //判断验证码是否输出正确
            //从redis中获取验证码
            String code = jedisPool.getResource().get(deviceId);
            //判断
            if (!code.equals(imgCode)) {
                return new Result(false,"验证码输入错误");
            }
            return new Result(true, "验证码输入正确");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "验证码输入错误");
        }
    }
}